<?php
declare (strict_types = 1);

namespace app\applet\controller;
use think\facade\Db;
use think\facade\Config;
class Index
{
    /**
     *静默操作 仅保存 openid
     * 进入页面直接将获取openid，并且将他存入wx_uesr表中，返回id进行其他操作
     **/
    public function setOpenid(){
        $data = request()->param();
        //接收code
        $code = $data['code'];
        $openid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.config('wx')['appletAppId'].'&secret='.config('wx')['appletAppSecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $openid_data = json_decode(req_Get($openid_url),true);
        $openid = $openid_data['openid'];
        $wx_user = Db::table("wxs_user")->where("wxs_openid",$openid)->find();
        //查询是否存储该用户
        if(!empty($wx_user)){
            return json(['status'=>200,"msg"=>"用户存在,返回数据成功",'wxs_id'=>$wx_user['wxs_id']]);
        }else{
            $wxs_id = Db::table("wxs_user")->insertGetId(['wxs_openid'=>$openid,'wxs_create_time'=>date('Y-m-d H:i:s')]);
            return json(['status'=>200,"msg"=>"用户身份已创建，返回数据成功",'wxs_id'=>$wxs_id]);
        }
    }
    /**
     *静默操作 保存用户信息
     * 进入页面直接将获取openid，并且将他存入wx_uesr表中，返回id进行其他操作
     * 用法：前端uni.getUserProfile将uni.login套在里头，发起请求
     **/
    public function setUserInfo(){
        $data = request()->param();
        //接收code
        $code = $data['code'];
        $openid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.config('wx')['appletAppId'].'&secret='.config('wx')['appletAppSecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $openid_data = json_decode(req_Get($openid_url),true);
        $openid = $openid_data['openid'];
        $wxs_user = Db::table("wxs_user")->where("wxs_openid",$openid)->find();
        /**
        DROP TABLE IF EXISTS `wxs_user`;

        CREATE TABLE `wxs_user` (
        `wxs_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
        `wxs_openid` varchar(50) DEFAULT NULL COMMENT '小程序获取微信openid',
        `wxs_nickName` varchar(255) DEFAULT NULL COMMENT '小程序获取微信昵称',
        `wxs_phone` char(11) DEFAULT NULL COMMENT '小程序获取手机号码',
        `wxs_avatarUrl` text COMMENT '小程序获取微信头像',
        `wxs_create_time` datetime DEFAULT NULL COMMENT '创建时间',
        PRIMARY KEY (`wxs_id`),
        KEY `wxs_id` (`wxs_id`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
         */
        //查询是否存储该用户
        if(!empty($wxs_user)){
            return json(['status'=>200,"msg"=>"用户存在,返回数据成功",'id'=>$wxs_user['wxs_id']]);
        }else{
            $result = [
                'wxs_openid'=>$openid,
                'wxs_nickName'=>$data['nickName'],
                'wxs_avatarUrl'=>$data['avatarUrl'],
                'wxs_create_time'=>date("Y-m-d H:i:s")
            ];

            $id = Db::table("wxs_user")->insertGetId($result);
            return json(['status'=>200,"msg"=>"用户身份已创建，返回数据成功",'wxs_id'=>$id]);
        }
    }
    /**
     * 发送订阅消息，此操作需要用户同意才可以接收到
     * $template_id 模板id
     * $openId 发送给哪个用户，取出openid
     * 其他自定义
    */
    public function sendApi($template_id,$openId,$sign_time,$sign_day,$sign_name,$sign_num,$msg){
        //先获取ACCESS_TOKEN
        $get_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('wx')['appletAppId'].'&secret='.config('wx')['appletAppSecret'];
        //请求得到全部access等全部信息
        $access_token_arr = json_decode(req_Get($get_access_token_url),true);
        $access_token = $access_token_arr['access_token'];
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
        //模板id 编号3436
        $udata['template_id'] = $template_id;
        $udata['touser'] = $openId;
        //发送的消息模板
        $udata['data'] = array(
            'date7'=>['value'=>$sign_time],//参观日期
            'character_string6'=>['value'=>$sign_day],//入馆时段
            'name1'=>['value'=>$sign_name],//姓名
            'number8'=>['value'=>$sign_num],//参观人数
            'thing9'=>['value'=>$msg]//"您的预约登记成功"
        );
        //跳转小程序类型developer为开发版；trial为体验版；formal为正式版；默认为正式版
        $udata['miniprogram_state'] = "trial";
        $udata['lang'] = "zh_CN";
        //var_dump(json_encode($udata));
        return req_Post($url,json_encode($udata));

    }
    //获取手机号码
    public function getPhone(){
        $data = request()->param();
        //接收code
        $code = $data['code'];
		//获取用户id
        $wxs_id = $data['wxs_id'];
        $time = time();
        $expires_in_time = Db::table("wxs_access_token")->where("access_id",1)->value("time");
        $access_token_value = Db::table("wxs_access_token")->where("access_id",1)->value("access_token_value");
        if($time > $expires_in_time){
            $this->getAccessToken();
            $access_token_value = Db::table("wxs_access_token")->where("access_id",1)->value("access_token_value");
        }
        $get_phone_url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token_value;
        $udata = [];
        $udata['code'] = $code;
        $reqest_data = json_decode(req_Post($get_phone_url,json_encode($udata)),true);
        //var_dump($reqest_data);
        if($reqest_data['errcode'] == 0 ){
            $phone = $reqest_data['phone_info']['phoneNumber'];
            $selectPhone = Db::table("wxs_user")->where("wxs_id",$wxs_id)->value('wxs_phone');
            $addPhone = Db::table("wxs_user")->where("wxs_id",$wxs_id)->update(['wxs_phone'=>$phone]);
            if(!empty($selectPhone)  || $addPhone){
                return json(['status'=> 200]);
            }else{
                return json(['status'=> 500]);
            }
        }else{
            return json(['status'=> 500]);
        }
    }
    //获取小程序link-url，会跳转到小程序详情页，点击确认才进小程序页面
    public function getAppletUrl(){
        $time = time();
        $expires_in_time = Db::table("wxs_access_token")->where("access_id",1)->value("time");
        $access_token_value = Db::table("wxs_access_token")->where("access_id",1)->value("access_token_value");
        if($time > $expires_in_time){
            $this->getAccessToken();
            $access_token_value = Db::table("wxs_access_token")->where("access_id",1)->value("access_token_value");
        }
        $get_url_link = 'https://api.weixin.qq.com/wxa/generate_urllink?access_token='.$access_token_value;
        $udata = [];
        $udata['path'] = '/pages/index2/index';
        $line_data = json_decode(req_Post($get_url_link,json_encode($udata))  ,true);
        if($line_data['errmsg'] == 'ok' ){
            return ['status'=>200,'data'=>$line_data['url_link']];
        }else{
            return ['status'=>500,'data'=>''];
        }

    }
    //获取小程序 scheme 码，可以直接跳转小程序页面
    public function getScheme(){
        $time = time();
        $expires_in_time = Db::table("wxs_access_token")->where("access_id",1)->value("time");
        $access_token_value = Db::table("wxs_access_token")->where("access_id",1)->value("access_token_value");
        if($time > $expires_in_time){
            $this->getAccessToken();
            $access_token_value = Db::table("wxs_access_token")->where("access_id",1)->value("access_token_value");
        }
        $get_scheme_link = 'https://api.weixin.qq.com/wxa/generatescheme?access_token='.$access_token_value;
        $udata = [];
        $udata['jump_wxa']['path'] = '/pages/index2/index';
        $scheme_data = json_decode(req_Post($get_scheme_link,json_encode($udata))  ,true);
        if($scheme_data['errmsg'] == 'ok' ){
            return ['status'=>200,'data'=>$scheme_data['openlink']];
        }else{
            return ['status'=>500,'data'=>''];
        }
    }
    protected function getAccessToken(){
        /**
         *
        CREATE TABLE `wxs_access_token` (
        `access_id` int(11) NOT NULL AUTO_INCREMENT ,
        `access_token_value` text NOT NULL,
        `time` bigint(20) NOT NULL,
        PRIMARY KEY (`access_id`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

        INSERT INTO `wxs_access_token` (`access_id`, `access_token_value`, `time`) VALUES ('1', 'sadsad', '451511');

         **/
        $appid = Config('wx')['appletAppId'];
        $appsecret = Config('wx')['appletAppSecret'];
        $get_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $access_token_arr = json_decode(req_Get($get_access_token_url),true);
        $access_token = $access_token_arr['access_token'];
        Db::table("wxs_access_token")->where("access_id",1)->update([
            "access_token_value"=>$access_token,
            "time"=>time()+7200
        ]);
    }




}
